<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title></title>
</head>
<body>
<div>发送消息</div>
<input type="text" id="msgContent"/>
<input type="button" value="点我发送" onclick="chat.chat1()"/>
<div>接受消息</div>
<div id="receiveMsg" style="background-color: gainsboro;"></div>
<script type="application/javascript">

    window.chat = {

        socket: null,
        init: function () {
            if (window.WebSocket) {
                chat.socket = new WebSocket("ws://127.0.0.1:8880/talk");
                chat.socket.onopen = function () {
                    console.log("连接建立成功");
                },
                    chat.socket.onclose = function () {
                        console.log("连接关闭");

                    },
                    chat.socket.onerror = function () {
                        console.log("连接出错");
                    },
                    chat.socket.onmessage = function (e) {
                        console.log("接受到消息" + e.data);
                        var receiveMsg = document.getElementById("receiveMsg");
                        var html = receiveMsg.innerHTML;
                        receiveMsg.innerHTML = html + "<br/>" + e.data;

                    }

            } else {
                alert("浏览器不支持协议");
            }

        },
        chat1: function () {
            var msg = document.getElementById("msgContent");
            chat.socket.send(msg.value);

        }

    };
    chat.init();
</script>
</body>
</html>